package org.eiahe.hr.interview.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.ehe.common.core.exception.ServiceException;
import org.ehe.common.core.utils.StringUtils;
import org.ehe.common.mybatis.core.page.PageQuery;
import org.ehe.common.mybatis.core.page.TableDataInfo;
import org.ehe.common.satoken.utils.LoginHelper;
import org.eiahe.hr.interview.analyzer.SimplifiedResumeAnalyzer;
import org.eiahe.hr.interview.domain.*;
import org.eiahe.hr.interview.domain.vo.InterviewBehaviorTestRecordsVO;
import org.eiahe.hr.interview.domain.vo.InterviewQuestionRecordVO;
import org.eiahe.hr.interview.domain.vo.InterviewRecordVO;
import org.eiahe.hr.interview.service.*;
import org.eiahe.hr.interview.domain.dto.InterviewRecordDTO;
import org.eiahe.hr.interview.domain.dto.InterviewRecordResultDTO;
import org.eiahe.hr.interview.mapper.InterviewBehaviorTestRecordsMapper;
import org.eiahe.hr.interview.mapper.InterviewRecordMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * 面试记录实体类
 * @author :zhangnn
 * @className :InterviewRecordServiceImpl
 * @description: TODO
 * @date 2025-08-14 09:39:36
 */
@Slf4j
@Service
@AllArgsConstructor
public class InterviewRecordServiceImpl extends ServiceImpl<InterviewRecordMapper, InterviewRecord> implements InterviewRecordService {

    private final InterviewCandidateService candidateService;
    private final SimplifiedResumeAnalyzer resumeAnalyzer;
    private final InterviewQuestionRecordService questionRecordService;
    private final InterviewQuestionService questionService;
    private final InterviewQuestionBankService bankService;
    private final InterviewBehaviorResultTypesService behaviorResultTypesService;
    private final InterviewBehaviorTestRecordsMapper behaviorTestRecordsMapper;
    /**
     * 分页
     * @param query
     * @param pageQuery
     * @return
     */
    @Override
    public TableDataInfo<InterviewRecordVO> selectRecordPage(InterviewRecordDTO query, PageQuery pageQuery) {
        QueryWrapper<InterviewRecord> lqw = buildQueryWrapper(query);
        IPage<InterviewRecordVO> page = this.baseMapper.selectRecordPage(pageQuery.build(),lqw);
        return TableDataInfo.build(page);
    }
    private QueryWrapper<InterviewRecord> buildQueryWrapper(InterviewRecordDTO query) {
        QueryWrapper<InterviewRecord> lqw = Wrappers.query();
        lqw.eq("r.del_flag",0);
        lqw.like(StringUtils.isNotBlank(query.getName()),"c.name",query.getName());
        lqw.like(StringUtils.isNotBlank(query.getPhone()),"c.phone",query.getPhone());
        lqw.like(StringUtils.isNotBlank(query.getIdCard()),"c.id_card",query.getIdCard());
        lqw.like(StringUtils.isNotBlank(query.getCategoryName()),"p.category_name",query.getCategoryName());
        lqw.eq(null != query.getStatus(),"r.status",query.getStatus());
        lqw.eq(null != query.getInterviewResult(),"r.interview_result",query.getInterviewResult());
        lqw.eq(null != query.getIsHired(),"r.is_hired",query.getIsHired());
        return lqw;
    }

    /**
     * 根据ID获取面试详情
     * @param id
     * @return
     */
    @Override
    public InterviewRecordVO selectById(Long id) {
        if (id == null) {
            throw new ServiceException("ID不能为空");
        }

        QueryWrapper<InterviewRecord> wrapper = new QueryWrapper<>();
        wrapper.eq("r.id", id);

        IPage<InterviewRecordVO> page = this.baseMapper.selectRecordPage(
            new com.baomidou.mybatisplus.extension.plugins.pagination.Page<>(1, 1),
            wrapper);

        List<InterviewRecordVO> records = page.getRecords();
        if (records.isEmpty()) {
            throw new ServiceException("面试记录不存在");
        }

        return records.get(0);
    }

    /**
     * 新增面试记录
     * @param dto
     * @return
     */
    @Override
    public boolean insertRecord(InterviewRecordDTO dto) {
        InterviewRecord record = new InterviewRecord();
        BeanUtils.copyProperties(dto,record);

        // 如果没有候选人ID，先创建候选人记录
        if (record.getCandidateId() == null) {
            Long candidateId = createOrFindCandidate(dto);
            record.setCandidateId(candidateId);
        }

        // 设置默认值
        if (record.getStatus() == null) {
            record.setStatus(0); // 待开始
            record.setInterviewDate(null);
        }
        if (record.getInterviewResult() == null) {
            record.setInterviewResult(3); // 待定
        }
        if (record.getIsHired() == null) {
            record.setIsHired(0); // 未录用
        }

        return this.save(record);
    }

    /**
     * 修改面试记录
     * @param id
     * @param dto
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateRecord(Long id, InterviewRecordDTO dto) {
        InterviewRecord existRecord = this.getById(id);
        if (existRecord == null) {
            throw new ServiceException("面试记录不存在");
        }

        InterviewRecord record = new InterviewRecord();
        BeanUtils.copyProperties(dto,record);
        record.setId(id);

        //更新候选人信息
        InterviewCandidate candidate = candidateService.getById(dto.getCandidateId());
        if(Objects.nonNull(candidate)){
            candidate.setName(dto.getName());
            candidate.setAge(dto.getAge());
            candidate.setIdCard(dto.getIdCard());
            candidate.setStatus(dto.getStatus());
            candidate.setPhone(dto.getPhone());
            candidate.setUpdateBy(LoginHelper.getUsername());
            candidateService.updateById(candidate);
        }

        return this.updateById(record);
    }

    /**
     * 删除面试记录
     * @param ids
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteByIds(List<String> ids) {
        if (ids == null || ids.isEmpty()) {
            throw new ServiceException("删除ID不能为空");
        }

        List<Long> longIds = ids.stream().map(Long::valueOf).toList();
        return this.removeBatchByIds(longIds);
    }

    /**
     * 简历解析
     * @param file
     * @param categoryId
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public InterviewRecordDTO parseResumeAndCreateRecord(MultipartFile file, Long categoryId) {
        try {
            // 解析简历
            InterviewRecordDTO dto = new InterviewRecordDTO();
            SimplifiedResumeAnalyzer.ResumeInfo resumeInfo = resumeAnalyzer.analyzeResumeFromMultipart(file);
            if (Objects.isNull(resumeInfo)) {
                throw new ServiceException("简历信息解析失败，请检查文件内容");
            }
            dto.setName(resumeInfo.getPersonalInfo().getName());
            dto.setPhone(resumeInfo.getPersonalInfo().getPhone());
            dto.setIdCard(resumeInfo.getPersonalInfo().getBirthDate());
            // 设置职位分类
            if (categoryId != null) {
                dto.setCategoryId(categoryId);
            }

            // 创建或查找候选人
            Long candidateId = createOrFindCandidate(dto);

            // 创建面试记录
            InterviewRecord record = new InterviewRecord();
            BeanUtils.copyProperties(dto,record);
            record.setCategoryId(categoryId);
            record.setCandidateId(candidateId);
            record.setStatus(0); // 进行中
            record.setInterviewResult(3); // 待定
            record.setIsHired(0); // 未录用

            this.save(record);

            log.info("简历解析并创建面试记录成功，记录ID：{}", record.getId());
            return dto;

        } catch (Exception e) {
            log.error("解析简历失败", e);
            throw new ServiceException("简历解析失败：" + e.getMessage());
        }
    }

    /**
     * 批量解析简历
     */
//    @Override
//    @Transactional(rollbackFor = Exception.class)
//    public int batchParseResume(MultipartFile[] files, Long categoryId) {
//        int successCount = 0;
//
//        for (MultipartFile file : files) {
//            try {
//                parseResumeAndCreateRecord(file, categoryId);
//                successCount++;
//            } catch (Exception e) {
//                log.error("批量处理简历失败，文件：{}", file.getOriginalFilename(), e);
//            }
//        }
//
//        return successCount;
//    }


    /**
     * 更新面试状态
     * @param id
     * @param status
     * @return
     */
    @Override
    public boolean updateInterviewStatus(Long id, Integer status) {
        InterviewRecord record = new InterviewRecord();
        record.setId(id);
        record.setStatus(status);
        if(status == 1){
            record.setInterviewDate(LocalDateTime.now());
        }
        return this.updateById(record);
    }

    /**
     * 更新面试结果
     * @return
     */
    @Override
    public boolean updateInterviewResult(InterviewRecordResultDTO dto) {
        InterviewRecord record = new InterviewRecord();
        record.setId(dto.getId());
        record.setInterviewResult(dto.getInterviewResult());
        record.setComments(dto.getComments());
        record.setTotalScore(dto.getTotalScore());
        record.setAvgScore(dto.getAvgScore());
        record.setBankId(dto.getBankId());

        // 如果结果是通过或不通过，同时更新状态为已完成
        //if (dto.getInterviewResult() == 1 || dto.getInterviewResult() == 2) {
            record.setStatus(2); // 已完成
        //}
        //保存面试题目信息
        List<InterviewQuestionRecord> questionRecordList = dto.getQuestionRecordList();
        questionRecordService.saveBatch(questionRecordList);

        return this.updateById(record);
    }

    /**
     * 更新录用状态
     * @param id
     * @param isHired
     * @return
     */
    @Override
    public boolean updateHireStatus(Long id, Integer isHired) {
        InterviewRecord record = new InterviewRecord();
        record.setId(id);
        record.setIsHired(isHired);
        return this.updateById(record);
    }

    /**
     * 创建或查找候选人
     */
    private Long createOrFindCandidate(InterviewRecordDTO dto) {
        // 先尝试通过手机号或身份证查找现有候选人
        InterviewCandidate existCandidate = null;

        if (StringUtils.isNotBlank(dto.getPhone())) {
            LambdaQueryWrapper<InterviewCandidate> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(InterviewCandidate::getPhone, dto.getPhone());
            existCandidate = candidateService.getOne(wrapper);
        }

        if (existCandidate == null && StringUtils.isNotBlank(dto.getIdCard())) {
            LambdaQueryWrapper<InterviewCandidate> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(InterviewCandidate::getIdCard, dto.getIdCard());
            existCandidate = candidateService.getOne(wrapper);
        }

        if (existCandidate != null) {
            return existCandidate.getId();
        }

        // 创建新的候选人记录
        InterviewCandidate candidate = new InterviewCandidate();
        candidate.setName(dto.getName());
        candidate.setAge(dto.getAge());
        candidate.setPhone(dto.getPhone());
        candidate.setIdCard(dto.getIdCard());
        candidate.setStatus(1);
        candidate.setCreateBy(LoginHelper.getUsername());
        candidate.setTenantId(LoginHelper.getTenantId());

        candidateService.save(candidate);
        return candidate.getId();
    }

    /**
     * 面试详情信息
     * @param id
     * @return
     */
    @Override
    public InterviewRecordVO detail(Long id,String flag) {
        InterviewRecordVO interviewRecordVO = selectById(id);
        //行为分析测试结果
        if(null != interviewRecordVO.getBankId()){
            InterviewQuestionBank bank = bankService.getById(interviewRecordVO.getBankId());
            if(bank.getInterviewType() == 2){ //行为测试
                List<InterviewBehaviorTestRecordsVO>   behaviorTestRecordsVOS = behaviorTestRecordsMapper.selectVoList(
                    new LambdaQueryWrapper<InterviewBehaviorTestRecords>()
                        .eq(InterviewBehaviorTestRecords::getUserId,interviewRecordVO.getCandidateId())
                        .eq(InterviewBehaviorTestRecords::getBankId,interviewRecordVO.getBankId())
                );

                InterviewBehaviorTestRecordsVO records = behaviorTestRecordsVOS.get(0);
                InterviewBehaviorResultTypes resultTypes = behaviorResultTypesService.selectByCode(records.getResultCode(),interviewRecordVO.getBankId());
                records.setBehaviorResultTypes(resultTypes);
                interviewRecordVO.setBehaviorTestRecordsVO(records);
                return interviewRecordVO;
            }
        }
        List<InterviewQuestionRecord> list = questionRecordService.list(new LambdaQueryWrapper<InterviewQuestionRecord>()
            .eq(InterviewQuestionRecord::getInterviewId, id)
            .orderByAsc(InterviewQuestionRecord::getQuestionOrder)
        );
        List<InterviewQuestionRecordVO> vos = new ArrayList<>();
        for (InterviewQuestionRecord interviewQuestionRecord : list) {
            InterviewQuestionRecordVO vo = new InterviewQuestionRecordVO();
            vo.setQuestionRecord(interviewQuestionRecord);
            InterviewQuestion question = questionService.getById(interviewQuestionRecord.getQuestionId());
            vo.setQuestion(question);
            vos.add(vo);
        }
        interviewRecordVO.setQuestionRecordVOList(vos);
        return interviewRecordVO;
    }
}
